﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.ComponentModel;
using deFramework;

namespace deFramework.Base
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseUserControl : System.Web.UI.UserControl
    {

        #region "Events - OnLoad"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            try
            {
                if (!this.WebPartIndicator)
                    this.IntegrateContext();
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            base.OnLoad(e);
        }


        #endregion

        #region "Properties - UserControlParameters"


        /// <summary>
        /// 
        /// </summary>
        [Browsable(true)]
        [Category("Site Integration")]
        [Description("Configurable Parameters for User Control")]
        public string UserControlParameters
        {
            get { return this._UserControlParameters; }
            set { _UserControlParameters = value; }
        }
        private string _UserControlParameters = String.Empty;


        #endregion 
        
        #region "public MyContext, public WebPartIndicator, private IntegrateContext"



        /// <summary>
        /// 
        /// </summary>
        public Common.PresentationContext MyContext = null;



        /// <summary>
        /// 
        /// </summary>
        public bool WebPartIndicator
        {
            get { return _WebPartIndicator; }
            set { this._WebPartIndicator = value; }
        }

        private bool _WebPartIndicator = false;

        private void IntegrateContext()
        {
            try
            {
                if (this.MyContext == null)
                {
                    Base.BaseSharePointPage oPage = (Base.BaseSharePointPage)this.Page;
                    this.MyContext = oPage.MyContext;
                }
                this.StandardLog("IntegrateContext", "user control OnLoad alert");

            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }

        }

        #endregion

        #region "Polymorphism - PageParamValue, SpWebPropertyValue, SetSpWebProperty, RemoveSpWebProperty"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aVariableName"></param>
        /// <param name="aDefault"></param>
        /// <returns></returns>
        public string PageParamValue(string aVariableName, string aDefault)
        {
            return this.MyContext.PageParamValue(aVariableName, aDefault);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <param name="aDefault"></param>
        /// <returns></returns>
        public string SpWebPropertyValue(string aPropertyName, string aDefault)
        {
            return this.MyContext.SpWebPropertyValue(aPropertyName, aDefault);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <param name="aValue"></param>
        /// <returns></returns>
        public bool SetSpWebProperty(string aPropertyName, string aValue)
        {
            return this.MyContext.SetSpWebProperty(aPropertyName, aValue);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aPropertyName"></param>
        /// <returns></returns>
        public bool RemoveSpWebProperty(string aPropertyName)
        {
            return this.MyContext.RemoveSpWebProperty(aPropertyName);
        }


        #endregion

        #region "Polymorphism - MyLog, CurrentException, StandardLog, GotoErrorPage"

        /// <summary>
        /// 
        /// </summary>
        public Common.FrameworkLogging MyLog
        {
            get { return this.MyContext.MyLog; }
        }

        /// <summary>
        /// 
        /// </summary>
        public System.Exception CurrentException
        {
            get
            {
                Exception _ex = null;
                try
                {
                    _ex = this.MyContext.CurrentException;
                }
                catch (Exception ex)
                {
                    _ex = ex;
                }
                return _ex;
            }
            set
            {
                Exception _ex = value;
                try
                {
                    this.MyContext.CurrentException = _ex;
                }
                catch
                {
                    // do nothing 
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aMethodName"></param>
        /// <param name="aMessage"></param>
        /// <returns></returns>
        public bool StandardLog(string aMethodName, string aMessage)
        {
            return this.MyContext.StandardLog(aMethodName, aMessage);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aTitle"></param>
        /// <param name="aDescription"></param>
        public void GotoErrorPage(string aTitle, string aDescription)
        {
            this.MyContext.GotoErrorPage(aTitle, aDescription);
        }


        #endregion

        #region "4 user control dependent methods -  GetWebServerCacheValue, SetWebServerCacheValue, GetSpFileForUrl, LoadSpFileItemAsInfoPathXmlDoc"




        /// <summary>
        /// 
        /// </summary>
        /// <param name="aVariableName"></param>
        /// <param name="aDefault"></param>
        /// <returns></returns>
        protected string GetWebServerCacheValue(string aVariableName, string aDefault)
        {
            string l_Result = aDefault;
            try
            {
                l_Result = this.Cache[aVariableName].ToString();
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return l_Result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="aVariableName"></param>
        /// <param name="aValue"></param>
        protected void SetWebServerCacheValue(string aVariableName, string aValue)
        {
            this.Cache[aVariableName] = aValue;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        protected Microsoft.SharePoint.SPFile GetSpFileForUrl(string url)
        {
            Microsoft.SharePoint.SPFile fileAtUrl = this.MyContext.MySpWeb.GetFile(url);
            if (fileAtUrl.Exists)
                return fileAtUrl;
            else
                throw new Exception("Unable to find Form file at " + url);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="infoPathFormUrl"></param>
        /// <param name="itemFile"></param>
        /// <returns></returns>
        protected System.Xml.XmlDocument LoadSpFileItemAsInfoPathXmlDoc(string infoPathFormUrl, out Microsoft.SharePoint.SPListItem itemFile)
        {
            itemFile = null;
            System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
            try
            {
                string url = infoPathFormUrl.Trim();
                if (url.IndexOf(",") > 1)
                    url = url.Substring(0, url.IndexOf(",") - 1).Trim();
                Microsoft.SharePoint.SPFile file = this.GetSpFileForUrl(url);
                itemFile = file.Item;
                xd.PreserveWhitespace = true;
                if (!(file == null))
                {
                    using (System.IO.MemoryStream inStream =
                        new System.IO.MemoryStream(file.OpenBinary()))
                    {
                        xd.Load(inStream);
                    }
                }
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return xd;
        }



        #endregion

        #region "2 User Control Javascript Utilities - RegisterJavascript, CheckBoxControlWithSetClickEvent"





        /// <summary>
        /// REUSE 
        /// </summary>
        /// <param name="scriptName"></param>
        /// <param name="scriptCode"></param>
        protected void RegisterJavascript(string scriptName, string scriptCode)
        {
            Type csType = typeof(deFramework.Base.BaseUserControl);
            this.Page.ClientScript.RegisterClientScriptBlock(csType,
                scriptName, scriptCode, true);
        }




        /// <summary>
        /// REUSE 
        /// </summary>
        /// <param name="controlName"></param>
        /// <param name="clickJavascriptFunctionName"></param>
        /// <returns></returns>
        protected System.Web.UI.WebControls.CheckBox CheckBoxControlWithSetClickEvent(
            string controlName, string clickJavascriptFunctionName)
        {
            System.Web.UI.WebControls.CheckBox cbx =
                (System.Web.UI.WebControls.CheckBox)this.FindControl(controlName);
            string eventScript = String.Format("javascript:{0}();", clickJavascriptFunctionName);
            cbx.Attributes.Add("onclick", eventScript);
            return cbx;
        }

        #endregion

        #region "2 BaseUserControl class dependent utilities - GetIntOverrideConfigVariableWithUserControlParamValue, GetOverrideConfigVariableWithUserControlParamValue"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="paramName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        protected int GetIntOverrideConfigVariableWithUserControlParamValue(string paramName, int defaultValue)
        {
            int result = defaultValue;
            string strResult = this.GetOverrideConfigVariableWithUserControlParamValue(paramName, defaultValue.ToString());
            try
            {
                result = Convert.ToInt32(strResult);
            }
            catch { }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="paramName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        protected string GetOverrideConfigVariableWithUserControlParamValue(string paramName, string defaultValue)
        {
            string result = defaultValue;
            string kXmlPrefix = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            try
            {
                xmlDoc.LoadXml(kXmlPrefix + this.UserControlParameters);
                System.Xml.XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode(paramName);
                if (!(xmlNode == null))
                {
                    string nodeValue = xmlNode.InnerXml;
                    result = nodeValue;
                }
            }
            catch { }
            return result;
        }


        #endregion 

        #region "37 Independent protected Methods - candidates for PresentationContext and polymorphism"

        // Methods not dependent upon the base user control class properties .... can be promoted to PresentationContext and/or helper classes for polymorphism 


        #region "5 methods - PercentageDisplayFormattingForZeroToOne, CurrentUserName, UserControlParameterHelpHtmlRow, HtmlForUserControlParametersHelp, CustomUserControlConfigurationStartValidityCheck"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rawValue"></param>
        /// <returns></returns>
        protected string PercentageDisplayFormattingForZeroToOne(string rawValue)
        {
            string _result = rawValue;
            try
            {
                decimal decPct = Convert.ToDecimal(rawValue);
                decPct = decPct * 100;
                _result = Convert.ToInt32(decPct).ToString();
            }
            catch { }

            return _result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="displayIndicator"></param>
        /// <returns></returns>
        protected string CurrentUserName(bool displayIndicator)
        {
            string _result = "((CURRENT USER NAME - ERROR - CALL SUPPORT))";
            try
            {
                if (displayIndicator)
                    _result = Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.Name;
                else
                    _result = Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName;
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return _result;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="parameterName"></param>
        /// <param name="description"></param>
        /// <param name="example"></param>
        /// <returns></returns>
        protected string UserControlParameterHelpHtmlRow(string parameterName, string description, string example)
        {
            string kLine = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>";
            return String.Format(kLine, parameterName, description, example);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pathAndControlName"></param>
        /// <param name="fieldsRows"></param>
        /// <param name="defaultUserControlParameters"></param>
        /// <returns></returns>
        protected string HtmlForUserControlParametersHelp(string pathAndControlName, string fieldsRows, string defaultUserControlParameters)
        {
            string lineHead1 = "&nbsp;<H4>&nbsp;" + pathAndControlName + ".ascx &nbsp; &nbsp; User  Control  Parameters  Help</H4>";
            string lineHead2 = "<table border=1><tr><td><b>Parameter</b></td><td><b>Description</b></td><td><b>Example</b></td></tr>";
            string lineFoot = "</table>&nbsp;&nbsp;<b>Example</b>:&nbsp;<input type=text size=120 value=\"" + defaultUserControlParameters + "\" />";

            string kHelp = "&nbsp;<br />{0}&nbsp;<br />{1}<br />&nbsp;<br />{2}&nbsp;<br />&nbsp;";
            return String.Format(kHelp, lineHead1 + lineHead2, fieldsRows, lineFoot);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="version"></param>
        /// <param name="helpHtml"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        protected bool CustomUserControlConfigurationStartValidityCheck(string version, string helpHtml, string errorMessage)
        {
            bool _result = false;
            try
            {
                //throw new Exception("sucks3"); 
                if (this.UserControlParameters.StartsWith(version))
                    _result = true;
                else if (this.UserControlParameters.Trim().ToLower() == "help")
                    this.PanelContent.InnerHtml = helpHtml;
                else if (this.UserControlParameters.Length > 1)
                    this.PanelContent.InnerHtml = errorMessage;
            }
            catch (Exception ex) { throw ex; }
            return _result;
        }

        #endregion 

        #region "3 dependent members - ShowErrorInPanel, PanelContent, PanelContentControlName"


        /// <summary>
        /// 
        /// </summary>
        protected void ShowErrorInPanel()
        {
            this.ShowCurrentExceptionInPanel(this.PanelContent);
        }

        /// <summary>
        /// 
        /// </summary>
        protected System.Web.UI.HtmlControls.HtmlGenericControl PanelContent
        {
            get { return (System.Web.UI.HtmlControls.HtmlGenericControl)this.FindControl(this.PanelContentControlName); }
        }


        /// <summary>
        /// 
        /// </summary>
        protected string PanelContentControlName = "divContent";



        #endregion

        #region "3 methods - ClearTextBoxValue, TextBoxPostbackValue, LabelPostbackValue"


        /// <summary>
        /// 
        /// </summary>
        /// <param name="controlName"></param>
        protected void ClearTextBoxValue(string controlName)
        {
            System.Web.UI.WebControls.TextBox tbx =
                         (System.Web.UI.WebControls.TextBox)this.FindControl(controlName);
            tbx.Text = String.Empty;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="controlName"></param>
        /// <returns></returns>
        protected string TextBoxPostbackValue(string controlName)
        {
            System.Web.UI.WebControls.TextBox tbx =
                 (System.Web.UI.WebControls.TextBox)this.FindControl(controlName);
            return tbx.Text;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="controlName"></param>
        /// <returns></returns>
        protected string LabelPostbackValue(string controlName)
        {
            System.Web.UI.WebControls.Label lbl =
                 (System.Web.UI.WebControls.Label)this.FindControl(controlName);
            return lbl.Text;
        }


        #endregion


        #region "5 Independent System.Data enhancement helpers - NewEmptyTable, RenderCustomHtmlForDataView, DataRowViewFieldStringValue, HeadingHtmlCellsForDataView, RowHtmlCellsForDataRowViews"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listColumnsCommaSeparated"></param>
        /// <returns></returns>
        protected System.Data.DataTable NewEmptyTable(string listColumnsCommaSeparated)
        {
            System.Data.DataTable result = new System.Data.DataTable();
            string[] fieldNames = listColumnsCommaSeparated.Split(',');
            foreach (string fieldName in fieldNames)
            {
                result.Columns.Add(new System.Data.DataColumn(fieldName));
            }

            return result;
        }


        #region "RenderCustomHtmlForDataView + 2 delegates"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public delegate string MethodDataRowViewAsRowInnerHtml(ref System.Data.DataRowView row);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public delegate string MethodHeadingRowInnerHtml(ref System.Data.DataView view);


        /// <summary>
        /// 
        /// </summary>
        /// <param name="oView"></param>
        /// <param name="headingHtmlMethod"></param>
        /// <param name="rowHtmlMethod"></param>
        /// <param name="tableAttributes"></param>
        /// <param name="headerAttributes"></param>
        /// <param name="rowAttributes"></param>
        /// <param name="altAttributes"></param>
        /// <returns></returns>
        public string RenderCustomHtmlForDataView(ref System.Data.DataView oView,
            MethodHeadingRowInnerHtml headingHtmlMethod,
            MethodDataRowViewAsRowInnerHtml rowHtmlMethod,
            string tableAttributes, string headerAttributes, string rowAttributes, string altAttributes)
        {
            string kTable = "<table {0}>{1}<table>";
            string kRow = "<TR {0}>{1}</TR>";
            string cellsHeading = headingHtmlMethod(ref oView);
            string htmlHeader = String.Format(kRow, headerAttributes, cellsHeading);

            string htmlRows = String.Empty;
            for (int i = 0; i < oView.Count; i++)
            {
                System.Data.DataRowView row = oView[i];
                string rowInnerHtml = rowHtmlMethod(ref row);
                if (i % 2 == 0)
                    htmlRows += String.Format(kRow, rowAttributes, rowInnerHtml);
                else
                    htmlRows += String.Format(kRow, altAttributes, rowInnerHtml);
            }

            return String.Format(kTable, headerAttributes, htmlHeader + htmlRows);
        }


        #endregion


        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <param name="fieldName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        protected string DataRowViewFieldStringValue(System.Data.DataRowView row, string fieldName, string defaultValue)
        {
            string result = defaultValue;
            try
            {
                result = row[fieldName].ToString();
            }
            catch { }
            return result;
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="oView"></param>
        /// <returns></returns>
        protected string HeadingHtmlCellsForDataView(ref System.Data.DataView oView)
        {
            string result = String.Empty;
            string kCellHtml = "<TH>{0}</TH>";
            foreach (System.Data.DataColumn col in oView.Table.Columns)
            {
                result += String.Format(kCellHtml, col.ColumnName);
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oRow"></param>
        /// <returns></returns>
        protected string RowHtmlCellsForDataRowViews(ref System.Data.DataRowView oRow)
        {
            string result = String.Empty;
            string kCellHtml = "<TD>{0}</TD>";

            foreach (System.Data.DataColumn col in oRow.DataView.Table.Columns)
            {
                result += String.Format(kCellHtml, oRow[col.ColumnName]);
            }
            return result;
        }




        #endregion

        #region "4 Independent SharePoint Content Helpers - OpenSpWeb, Url4UserWhoLastModifiedItem, Url4ListItemView, Url4ListDefaultView"





        /// <summary>
        /// 
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <returns></returns>
        protected Microsoft.SharePoint.SPWeb OpenSpWeb(string siteUrl)
        {
            Microsoft.SharePoint.SPSite objSite = new Microsoft.SharePoint.SPSite(siteUrl);
            string webUrl = siteUrl.Substring(objSite.Url.Length);
            Microsoft.SharePoint.SPWeb objWeb = objSite.OpenWeb(webUrl);
            return objWeb;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        protected string Url4UserWhoLastModifiedItem(Microsoft.SharePoint.SPListItem item)
        {
            string kUserViewUrlTemplate = "{0}/_layouts/userdisp.aspx?ID={1}";
            string webUrlPart = item.Web.Url;
            string modUser = item["Editor"].ToString();
            string idUser = modUser.Substring(0, modUser.IndexOf("#") - 1);
            return String.Format(kUserViewUrlTemplate, webUrlPart, idUser);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        protected string Url4ListItemView(Microsoft.SharePoint.SPListItem item)
        {
            string kDisplayListItemUrlTemplate = "{0}/{1}?ID={2}";
            string webUrlPart = item.Web.Url;
            string listUrlItemPart = item.ParentList.Forms[Microsoft.SharePoint.PAGETYPE.PAGE_DISPLAYFORM].Url;
            int itemId = item.ID;
            return String.Format(kDisplayListItemUrlTemplate,
                webUrlPart, listUrlItemPart, itemId.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        protected string Url4ListDefaultView(Microsoft.SharePoint.SPList list)
        {
            string kListDefaultViewUrlTemplate = "{0}/{1}";
            string webUrlPart = list.ParentWeb.Site.Url;
            string listUrlDefaultPart = list.DefaultViewUrl;
            return String.Format(kListDefaultViewUrlTemplate, webUrlPart, listUrlDefaultPart);
        }

        #endregion 

        #region "5 Independent HTML helpers - HtmlForLinkButton, HtmlForVersionLinkButton, AnchorHtml, HtmlSelectOption, GenericHtmlCell"


        /// <summary>
        /// 
        /// </summary>
        /// <param name="urlLink"></param>
        /// <param name="urlImage"></param>
        /// <param name="anchorAttribs"></param>
        /// <returns></returns>
        protected string HtmlForLinkButton(string urlLink, string urlImage, string anchorAttribs)
        {
            string kPreHtml1 = "<a href=\"{0}\" {1} Border=0>";
            string kPreHtml2 = "<img src='{2}' Border=0 /></a>&nbsp;";
            string html = String.Format(kPreHtml1 + kPreHtml2,
                urlLink, anchorAttribs, urlImage);
            return html;
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="listEncodedGuid"></param>
        /// <param name="itemId"></param>
        /// <param name="anchorAttribs"></param>
        /// <returns></returns>
        protected string HtmlForVersionLinkButton(string listEncodedGuid, int itemId, string anchorAttribs)
        {
            string kImageUrlVersions = "/_layouts/images/versions.gif";
            string kItemVersionHistoryUrlForEncodedListGuidAndItemId =
                "/_layouts/Versions.aspx?list={0}&Id={1}";
            string urlLink = String.Format(kItemVersionHistoryUrlForEncodedListGuidAndItemId,
                listEncodedGuid, itemId.ToString());
            return this.HtmlForLinkButton(urlLink, kImageUrlVersions, anchorAttribs);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="displayText"></param>
        /// <param name="emptyText"></param>
        /// <returns></returns>
        protected string AnchorHtml(string url, string displayText, string emptyText)
        {
            if (displayText.Length == 0)
                displayText = emptyText;
            string kAnchorHtml = "<A HREF=\"{0}\">{1}</A>";
            string result = String.Format(kAnchorHtml, url, displayText);
            return result;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="isSelected"></param>
        /// <param name="optionText"></param>
        /// <returns></returns>
        protected string HtmlSelectOption(bool isSelected, string optionText)
        {
            string stringSelected = String.Empty;
            if (isSelected) stringSelected = " selected";
            string kHtml = "<option{0}>{1}</option>";
            return String.Format(kHtml, stringSelected, optionText);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="contentsHtml"></param>
        /// <returns></returns>
        protected string GenericHtmlCell(string attributes, string contentsHtml)
        {

            string kCell = "<td {0}>{1}</td>";
            return String.Format(kCell, attributes, contentsHtml);
        }



        #endregion

        #region "2 Independent String Biz Helper Utilities - SimplifiedDateTimeDisplay, SharePointUserFieldValueDisplayName"

        /// <summary>
        /// Used by HtmlCell_Created 
        /// </summary>
        /// <param name="dateTimeString"></param>
        /// <returns></returns>
        protected string SimplifiedDateTimeDisplay(string dateTimeString)
        {
            int delimDateTime = dateTimeString.Trim().IndexOf(" ");

            string dateString = dateTimeString.Substring(0, delimDateTime).Trim();
            int intDayPos1 = dateString.IndexOf("/");
            int intDayPos2 = dateString.Substring(intDayPos1 + 1).IndexOf("/");
            dateString = dateString.Substring(0, intDayPos1 + intDayPos2 + 1);

            string timeString = dateTimeString.Substring(delimDateTime + 1).Trim();
            int intTimePos1 = timeString.IndexOf(":");
            int intTimePos2 = intTimePos1 + 3; // timeString.Substring(intTimePos1 + 1).IndexOf(":");
            if (timeString.ToUpper().Contains("PM"))
            {
                int hrs = 12 + Convert.ToInt32(timeString.Substring(0, intTimePos1));
                timeString = hrs.ToString() + timeString.Substring(intTimePos1, 3);
                //timeString = "17:59"; 
            }
            else
            {
                timeString = timeString.Substring(0, intTimePos2);
            }

            return dateString + " " + timeString;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="rawSharePointUserNameDataRowFieldValue"></param>
        /// <returns></returns>
        protected string SharePointUserFieldValueDisplayName(string rawSharePointUserNameDataRowFieldValue)
        {
            string result = rawSharePointUserNameDataRowFieldValue;
            try
            {
                int posDelimiter = rawSharePointUserNameDataRowFieldValue.IndexOf(";#");
                result = rawSharePointUserNameDataRowFieldValue.Substring(posDelimiter + 2);
            }
            catch { }
            return result;
        }

#endregion 

        #region "3 Independent String Biz Helpers - StringWithNonAlphaNumCharsExcluded, StringWithQuotesAndNewLinesExcluded, StringWithExteriorNodeExcluded" 

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        protected string StringWithNonAlphaNumCharsExcluded(string inputString)
        {
            string result = String.Empty;
            for (int i = 0; i < inputString.Length; i++)
            {
                char charUpper = inputString.ToUpper()[i];
                if (((charUpper >= 'A') && (charUpper <= 'Z')) || ((charUpper >= '1') && (charUpper <= '9')))
                    result += inputString.Substring(i, 1);
            }
            return result;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="rawString"></param>
        /// <returns></returns>
        protected string StringWithQuotesAndNewLinesExcluded(string rawString)
        {
            string result = rawString.Replace(System.Environment.NewLine, "  ");
            int posApost = 1;
            while (posApost >= 1)
            {
                posApost = result.IndexOf("'");
                if (posApost > 0 && result.Length > posApost)
                    result = result.Substring(0, posApost) + result.Substring(posApost + 1);
            }
            posApost = 1;
            while (posApost >= 1)
            {
                posApost = result.IndexOf("\"");
                if (posApost > 0 && result.Length > posApost)
                    result = result.Substring(0, posApost) + result.Substring(posApost + 1);
            }
            return result.Trim();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="rawHtml"></param>
        /// <returns></returns>
        protected string StringWithExteriorNodeExcluded(string rawHtml)
        {
            string rawBeforeStart = String.Empty;
            string rawAfterStart = rawHtml;
            int posStartTag = rawHtml.IndexOf("<");
            if (posStartTag >= 0)
            {
                if (posStartTag > 0)
                    rawBeforeStart = rawHtml.Substring(0, posStartTag);
                rawAfterStart = String.Empty;
                if (posStartTag + 1 < rawHtml.Length)
                    rawAfterStart = rawHtml.Substring(posStartTag + 1);
                int posSpace = rawAfterStart.IndexOf(" ");
                int posTagEnd = rawAfterStart.IndexOf(">");
                if (posTagEnd < posSpace) posSpace = posTagEnd;
                if (posSpace > 0)
                {
                    string tagName = rawAfterStart.Substring(0, posSpace);
                    string interiorHtml = String.Empty;
                    if (posTagEnd + 1 < rawHtml.Length)
                        interiorHtml = rawAfterStart.Substring(posTagEnd + 1);
                    int posEndName = interiorHtml.IndexOf("</" + tagName + ">");
                    if (posEndName > 0)
                        rawAfterStart = interiorHtml.Substring(0, posEndName);
                }
            }
            string result = rawBeforeStart + " " + rawAfterStart;
            return this.StringWithQuotesAndNewLinesExcluded(result);
        }



        #endregion

        #region "4 Independent SharePoint ListItem helpers - ItemToDebugString, ListItemFieldValue, AssignUserToListItemField, SetListItemPersonFieldValue"




        /// <summary>
        /// Use for debugging/displaying the contents of a ListItem 
        /// </summary>
        /// <remarks>
        /// 1. Add a CDATA clause
        /// </remarks>
        /// <param name="myItem">reference to ListItem object</param>
        /// <returns>an ugly but displayable results with values</returns>
        /// <example>[item [fld guid=xxx-xxx-xxxx-xxxx title=My Field internal=My_x0020x_Field xpath=blah value=Wow ][fld guid=xxx-xxx-xxxx-xxxx title=My Field internal=My_x0020x_Field xpath=blah value=Wow ] item]</example>
        protected string ItemToDebugString(Microsoft.SharePoint.SPListItem myItem)
        {
            string result = String.Empty;
            for (int i = 0; i < myItem.Fields.Count; i++)
            {
                Microsoft.SharePoint.SPField fld = myItem.Fields[i];
                string fldGuid = "[GUID]";
                try
                {
                    fldGuid = fld.Id.ToString();
                }
                catch { }
                string fldTitle = "[Title]";
                try
                {
                    fldTitle = fld.Title;
                }
                catch { }
                string fldInternal = "[Internal]";
                try
                {
                    fldInternal = fld.InternalName;
                }
                catch { }
                string fldXPath = "[XPath]";
                try
                {
                    fldXPath = fld.XPath;
                }
                catch { }
                string fldValue = "[Value]";
                try
                {
                    object objValue = myItem[i];
                    fldValue = objValue.ToString();
                }
                catch { }
                string kFieldDisplay = "[fld guid={0} title={1} internal={2} xpath={3} value={4} ]";
                string fieldDisplay = String.Format(kFieldDisplay,
                    fldGuid, fldTitle, fldInternal, fldXPath, fldValue);
                result += fieldDisplay;

                //    htmlInner += col.ColumnName + "=" + row[col.ColumnName].ToString() + "; ";
                //    if (col.ColumnName == "ID")
                //        valueID = row[col.ColumnName].ToString();
                //    else if (col.ColumnName == this.FieldNameFusionStatus)
                //        valueStatus = row[col.ColumnName].ToString();
                //    else if (col.ColumnName == this.FieldNameTrackingNumber)
                //        valueTracking = row[col.ColumnName].ToString();
            }
            return String.Format("[item {0} item]", result);
        }

   


        /// <summary>
        /// 
        /// </summary>
        /// <param name="oItem"></param>
        /// <param name="fieldName"></param>
        /// <param name="emptySubstituteValue"></param>
        /// <returns></returns>
        protected string ListItemFieldValue(Microsoft.SharePoint.SPListItem oItem,
            string fieldName, string emptySubstituteValue)
        {
            string _result = emptySubstituteValue;
            try
            {
                _result = oItem[fieldName].ToString();
            }
            catch { }
            if (_result == null || _result == String.Empty)
                _result = emptySubstituteValue;
            return _result;
        }




        /// <summary>
        /// Assign a user to a particular SharePoint list item field; and allow for specifying whether the change is done if 
        /// a value was previously assigned. 
        /// </summary>
        /// <param name="objectListItem">the object reference to the SharePoint list item</param>
        /// <param name="fieldName">name of the field in the list item to make change</param>
        /// <param name="nameUser">name of the user who will be assigned as value of this field</param>
        /// <param name="changeIndicatorIfAlreadySet">Whether or not to change if the field value already has a user assigned</param>
        protected void AssignUserToListItemField(ref Microsoft.SharePoint.SPListItem objectListItem,
            string fieldName, string nameUser, bool changeIndicatorIfAlreadySet)
        {

            bool proceedWithAssign = changeIndicatorIfAlreadySet;
            if (!proceedWithAssign)
            {
                string valueCurrent = String.Empty;
                try
                {
                    for (int i = 1; i < objectListItem.Fields.Count; i++)
                    {
                        Microsoft.SharePoint.SPField fld = objectListItem.Fields[i];
                        if (fld.ToString() == fieldName)
                        {
                            valueCurrent = objectListItem[i].ToString();
                            break;
                        }
                    }
                }
                catch { }
                proceedWithAssign = (valueCurrent == String.Empty);
            }
            if (proceedWithAssign)
            {
                this.SetListItemPersonFieldValue(ref objectListItem, fieldName, nameUser);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="oItem"></param>
        /// <param name="fieldName"></param>
        /// <param name="personNameDisplay"></param>
        /// <returns></returns>
        protected bool SetListItemPersonFieldValue(ref Microsoft.SharePoint.SPListItem oItem, string fieldName, string personNameDisplay)
        {
            bool _result = false;
            Guid guidField = this.FindItemUserFieldGuid(oItem, fieldName);
            _result = this.SetPersonListItemFieldValue(ref oItem, guidField, personNameDisplay);
            return _result;
        }

 


 
        #region "private SetListItemPersonFieldValue subs - FindItemUserFieldGuid, SetPersonListItemFieldValue"

        private Guid FindItemUserFieldGuid(Microsoft.SharePoint.SPListItem oItem, string fieldName)
        {
            Microsoft.SharePoint.SPList oList = oItem.ParentList;
            Guid guidField = new Guid();
            for (int i = 1; i < oList.Fields.Count; i++)
            {
                Microsoft.SharePoint.SPField fld = oList.Fields[i];
                if (fld.TypeAsString.ToUpper() == "USER" && fld.ToString() == fieldName)
                {
                    guidField = fld.Id;
                    break;
                }
            }
            return guidField;
        }

        private bool SetPersonListItemFieldValue(ref Microsoft.SharePoint.SPListItem oItem, Guid guidField, string nameDisplay)
        {
            bool _result = false;
            try
            {
                foreach (Microsoft.SharePoint.SPUser userRecord in oItem.Web.SiteUsers)
                {
                    if (userRecord.Name == nameDisplay)
                    {
                        string loginName = userRecord.LoginName;
                        oItem[guidField] = oItem.Web.EnsureUser(loginName);
                        _result = true;
                    }
                }
            }
            catch { }
            return _result;
        }

        #endregion




        #endregion 

        #region "3 Independent Methods - ShowCurrentExceptionInPanel, InfoPathFormStringValue, GetXmlDocNodesList"


        /// <summary>
        /// 
        /// </summary>
        /// <param name="panel"></param>
        protected void ShowCurrentExceptionInPanel(System.Web.UI.HtmlControls.HtmlGenericControl panel)
        {
            string kErrorDisplay = "<P>Error Message:&nbsp;{0}</P><P>Error Stack Trace:&nbsp;{1}</P>";
            panel.InnerHtml = String.Format(kErrorDisplay,
                this.CurrentException.Message, this.CurrentException.StackTrace);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xPath"></param>
        /// <param name="defaultValue"></param>
        /// <param name="xmlDoc"></param>
        /// <param name="xnm"></param>
        /// <returns></returns>
        protected string InfoPathFormStringValue(string xPath, string defaultValue,
            ref System.Xml.XmlDocument xmlDoc, ref System.Xml.XmlNamespaceManager xnm)
        {
            string nodeValue = defaultValue;
            try
            {
                if (!(xmlDoc == null) && !(xnm == null))
                {
                    System.Xml.XmlNode curNode = xmlDoc.SelectSingleNode(
                        xPath, xnm);
                    nodeValue = curNode.InnerText.ToString();
                }
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return nodeValue;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="docXml"></param>
        /// <param name="xmlNM"></param>
        /// <param name="xpath"></param>
        /// <returns></returns>
        protected System.Xml.XmlNodeList GetXmlDocNodesList(string xpath, ref System.Xml.XmlDocument docXml, ref System.Xml.XmlNamespaceManager xmlNM)
        {
            System.Xml.XmlNodeList _result = null;
            if (!(docXml == null))
            {
                System.Xml.XmlNode node = docXml.SelectSingleNode(
                         xpath, xmlNM);
                if (!(node == null))
                    _result = node.ChildNodes;
            }
            return _result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="nodeParent"></param>
        /// <param name="xpath"></param>
        /// <param name="defaultValue"></param>
        /// <param name="xmlNM"></param>
        /// <returns></returns>
        protected string NodeSubNodeValue(System.Xml.XmlNode nodeParent, string xpath, string defaultValue, System.Xml.XmlNamespaceManager xmlNM)
        {
            string _result = defaultValue;
            try
            {
                _result = nodeParent.SelectSingleNode(xpath, xmlNM).InnerText;
            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            return _result;
        }


        #endregion

    
        #endregion

        #region "Obsolete Properties - LinkToPageUrl, LinkToParamName, IntakeParamName, ExitToPageUrl"

        /// <summary>
        /// 
        /// </summary>
        [Browsable(true)]
        [Category("Site Integration")]
        [Description("The name of the Link To Page Url")]
        public string LinkToPageUrl
        {
            get { return this._LinkToPageUrl; }
            set { _LinkToPageUrl = value; }
        }

        private string _LinkToPageUrl = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        [Browsable(true)]
        [Category("Site Integration")]
        [Description("The name of the Link To Page Url")]
        public string LinkToParamName
        {
            get { return this._LinkToParamName; }
            set { _LinkToParamName = value; }
        }
        private string _LinkToParamName = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        [Browsable(true)]
        [Category("Site Integration")]
        [Description("The name of the Intake Param Name")]
        public string IntakeParamName
        {
            get { return this._IntakeParamName; }
            set { this._IntakeParamName = value; }
        }
        private string _IntakeParamName = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        [Browsable(true)]
        [Category("Site Integration")]
        [Description("The name of the Exit To Page Url")]
        public string ExitToPageUrl
        {
            get { return this._ExitToPageUrl; }
            set { _ExitToPageUrl = value; }
        }
        private string _ExitToPageUrl = String.Empty;


        #endregion

    }

}



#region "Dead Code" 


///// <summary>
///// REDO
///// </summary>
///// <param name="scriptName"></param>
///// <param name="scriptCode"></param>
//protected void RegisterJavascript(string scriptName, string scriptCode)
//{
//    Type csType = this.GetType();
//    this.Page.ClientScript.RegisterClientScriptBlock(csType,
//        scriptName, scriptCode);
//}





//protected string ListItemVersionHistoryUrl(string listEncodedGuid, int itemId)
//{


//}


#endregion 